package com.zrj.gulimall.controller;

import com.alibaba.fastjson.TypeReference;
import com.zrj.common.constant.AuthServerConstant;
import com.zrj.common.utils.R;
import com.zrj.common.vo.MemberResponseVo;
import com.zrj.gulimall.feign.MemberFeignService;
import com.zrj.gulimall.utils.ConstantWxUtils;
import com.zrj.gulimall.utils.HttpClientUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;

/**
 * @author zhaorujie
 * @version 1.0
 * @Description
 * @date 2021/2/2 15:22
 */
@Slf4j
@Controller
@RequestMapping(value = "/api/ucenter/wx")
public class WxApiController {

    @Autowired
    private MemberFeignService memberFeignService;

    /**
     * 获取扫码人的信息，添加数据
     * @return
     */
    @GetMapping(value = "/callback")
    public String callback(String code,String state, HttpSession session) throws Exception {
        try {
            //得到授权码临时票据code
            System.out.println(code);
            System.out.println(state);
            //从redis中将state获取出来，和当前传入的state作比较
            //如果一致则放行，如果不一致就抛出异常：非法访问

            //向认证服务器请求换取access_token
            //2、拿着code请求 微信固定的地址，得到两个access_token和openid
            String baseAccessTokenUrl = "https://api.weixin.11.com/sns/oauth2/access_token" +
                    "?appid=&s" +
                    "&secret=%s" +
                    "&code=%s" +
                    "&grant_type=authorization_code";

            //拼接三个参数：id 秘钥和code值
            String accessTokenUrl = String.format(
                    baseAccessTokenUrl,
                    ConstantWxUtils.WX_OPEN_APP_ID,
                    ConstantWxUtils.WX_OPEN_APP_SECRET,
                    code
            );

            String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);
            R r = memberFeignService.weixinLogin(accessTokenInfo);
            if (r.getCode() == 0) {
                MemberResponseVo data = r.getData("data", new TypeReference<MemberResponseVo>() {
                });
                log.info("登录成功：用户信息：{}",data.toString());

                //1、第一次使用session，命令浏览器保存卡号， JSESSIONID这个歌cookie
                //以后浏览器访问那一个网站就会带上这个网站的cookie
                //TODO 1、默认发的令牌。当前域（解决子域session共享问题）
                //TODO 2、使用JSON的序列化方式来序列化对象到redis中
                session.setAttribute(AuthServerConstant.LOGIN_USER, data);

                //2、登陆成功调回首页
                return "redirect:http://gulimall.com";
            }else {
                return "redirect:http://auth.gulimall.com/login.html";
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:http://auth.gulimall.com/login.html";
    }
}
